package com.seasugar.raggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seasugar.raggie.common.BaseContext;
import com.seasugar.raggie.mapper.OrderMapper;
import com.seasugar.raggie.model.entity.*;
import com.seasugar.raggie.model.vo.OrderVo;
import com.seasugar.raggie.service.AddressBookService;
import com.seasugar.raggie.service.OrderDetailService;
import com.seasugar.raggie.service.OrderService;
import com.seasugar.raggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    //试探事务
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private AddressBookService addressBookService;

    @Override
    @Transactional
    public void submit(Orders orders, HttpSession session) {
        User user = (User) session.getAttribute("user");
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        //订单插入一条数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        //判断购物车是否为空
//        if(shoppingCarts==null|| shoppingCarts.size()==0)
//            throw new Exception();

        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);


        //原子操作
        AtomicInteger amount = new AtomicInteger(0);
        LambdaQueryWrapper<ShoppingCart> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList1 = shoppingCartService.list(queryWrapper1);
        for (ShoppingCart shoppingCart : shoppingCartList1) {
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            log.info(String.valueOf(amount));
        }

        log.info(String.valueOf(amount));
        //订单号id
        Long orderId = IdWorker.getId();
        orders.setNumber(String.valueOf(orderId));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(String.valueOf(amount)));//总金额
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));


        this.save(orders);

        //订单明细插入多条数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper2=new LambdaQueryWrapper<>();
        queryWrapper2.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper2);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //反正也要清除购物车Id，直接拿来用
            orderDetail.setId(shoppingCart.getId());
            orderDetail.setOrderId(orderId);
            orderDetailService.save(orderDetail);
        }


        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }

    @Override
    public Page<OrderVo> getPage(Page pageInfo) {
        //新添orderDetail
        Page<OrderVo> page=new Page<>();
        BeanUtils.copyProperties(pageInfo,page,"records");
        //数据
        List<Orders> records = pageInfo.getRecords();
        List<OrderVo> list=new LinkedList<>();
        for (Orders record : records) {
            OrderVo orderVo=new OrderVo();
            BeanUtils.copyProperties(record,orderVo);
            LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,record.getNumber());
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);
            orderVo.setOrderDetails(orderDetails);
            list.add(orderVo);
        }
        page.setRecords(list);

        //形参改变并不会改变实参
        //        pageInfo=page;

        return page;
    }
}
